package csel.model;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.log4j.Logger;

public final class ObsHelper<T> implements java.io.Serializable
{
	private static final long serialVersionUID = 5L;
	
	private static final Logger logger = Logger.getLogger("csel.model");

	private final List<Observer<T>> intObservers = new CopyOnWriteArrayList<Observer<T>>();
	private transient List<Observer<T>> extObservers = new CopyOnWriteArrayList<Observer<T>>();
	
	private final Object source;
	
	public ObsHelper(Object source)
	{
		this.source = source;
	}
	
	public void add(Observer<T> o)
	{
		if (o.getClass().getName().contains("csel.model"))
		{
			logger.debug(String.format("Added internal observer (%s).", o));
			intObservers.add(o);
		}
		else
		{
			logger.debug(String.format("Added external observer (%s).", o));
			extObservers.add(o);
		}
	}

	public boolean remove(Observer<T> o)
	{
		return intObservers.remove(o);
	}
	
	public void notifyO(T param)
	{
		for (Observer<T> o : intObservers)
			o.mupdate(source, param);
		
		for (Observer<T> o : extObservers)
			o.mupdate(source, param);
	}
	
	private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException
	{
		in.defaultReadObject();
		
		extObservers = new CopyOnWriteArrayList<Observer<T>>();
	}
}
